<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, computed, watch, getCurrentInstance } from "vue";
import { useLabelm } from "./utils/hook";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import type { FormItemProps } from "./utils/types";
import { unitDelete } from "@/api/basicArchives/meterUnit";

import More2Fill from "@iconify-icons/ri/more-2-fill";
import AddIcon from "@iconify-icons/ep/plus";
import EditIcon from "@iconify-icons/ep/edit";
import DelIcon from "@iconify-icons/ep/delete";
import ExpandIcon from "@/assets/svg/expand.svg?component";
import UnExpandIcon from "@/assets/svg/unexpand.svg?component";

interface Tree {
  id: number;
  unitName: string;
  highlight?: boolean;
  children?: Tree[];
}

defineProps({
  treeLoading: Boolean,
  treeData: Array
});

const emit = defineEmits(["tree-select", "load-tree"]);

const treeRef = ref();
const isExpand = ref(true);
const searchValue = ref("");
const highlightMap = ref({});
const { proxy } = getCurrentInstance();
const defaultProps = {
  children: "children",
  label: "unitName"
};

const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.unitName.includes(value);
};

function nodeClick(value) {
  const nodeId = value.id;
  highlightMap.value[nodeId] = highlightMap.value[nodeId]?.highlight
    ? Object.assign({ id: nodeId }, highlightMap.value[nodeId], {
        highlight: false
      })
    : Object.assign({ id: nodeId }, highlightMap.value[nodeId], {
        highlight: true
      });
  Object.values(highlightMap.value).forEach((v: Tree) => {
    if (v.id !== nodeId) {
      v.highlight = false;
    }
  });
  emit(
    "tree-select",
    highlightMap.value[nodeId]?.highlight
      ? Object.assign({ ...value, selected: true })
      : Object.assign({ ...value, selected: false })
  );
}

/** 删除菜单 */
const delTree = async (treeData: FormItemProps) => {
  ElMessageBox.confirm(
    `确认要<strong>删除</strong><strong style='color:var(--el-color-primary)'>${
      treeData.unitName
    }</strong>单位吗?`,
    "系统提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }
  ).then(async () => {
    await unitDelete(treeData.id);
    message("删除成功", {
      type: "success"
    });
    emit("load-tree");
  });
};

function toggleRowExpansionAll(status) {
  isExpand.value = status;
  const nodes = (proxy.$refs["treeRef"] as any).store._getAllNodes();
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].expanded = status;
  }
}

/** 重置部门树状态（选中状态、搜索框值、树初始化） */
function onTreeReset() {
  highlightMap.value = {};
  searchValue.value = "";
  toggleRowExpansionAll(true);
}

watch(searchValue, val => {
  treeRef.value!.filter(val);
});

/** 设置当前选择的tree */
function setCurrentKey(treeId: number) {
  highlightMap.value[treeId] = {
    id: treeId,
    highlight: true
  };
}

defineExpose({ onTreeReset, setCurrentKey });

const { openDialog, hasAuth } = useLabelm(treeRef);
</script>

<template>
  <div
    v-loading="treeLoading"
    class="h-full bg-bg_color overflow-hidden relative"
    :style="{ minHeight: `calc(100vh - 141px)` }"
  >
    <div class="flex items-center justify-between h-[45px] ml-2 mr-2">
      <div class="font-bold">单位分类</div>
      <el-button
        v-if="hasAuth('unit:btn:add')"
        type="primary"
        size="small"
        @click="openDialog('新增')"
      >
        新增
      </el-button>
    </div>

    <el-divider />
    <div class="flex items-center h-[42px] ml-2 mr-2">
      <el-input v-model="searchValue" placeholder="搜索单位" clearable>
        <template #suffix>
          <el-icon class="el-input__icon">
            <IconifyIconOffline
              v-show="searchValue.length === 0"
              icon="ri:search-line"
            />
          </el-icon>
        </template>
      </el-input>
    </div>

    <el-scrollbar class="pl-[5px]">
      <el-tree
        ref="treeRef"
        :data="treeData"
        node-key="id"
        size="small"
        :indent="10"
        :props="defaultProps"
        default-expand-all
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        @node-click="nodeClick"
      >
        <template #default="{ node, data }">
          <div
            :class="[
              'h-full',
              'w-[80%]',
              'font-bold',
              'rounded',
              'flex',
              'items-center',
              'select-none',
              'hover:text-primary',
              'pr-2',
              searchValue.trim().length > 0 &&
                node.label.includes(searchValue) &&
                'text-red-500',
              highlightMap[data.id]?.highlight ? 'dark:text-primary' : ''
            ]"
            :style="{
              color: highlightMap[data.id]?.highlight
                ? 'var(--el-color-primary)'
                : '',
              background: highlightMap[data.id]?.highlight
                ? 'var(--el-color-primary-light-7)'
                : 'transparent'
            }"
          >
            <!-- <IconifyIconOffline v-if="node.level == 1" :icon="MenuIcon" /> -->
            <div class="!w-[190px] !truncate pl-[5px]" :title="node.label">
              {{ node.label }}
            </div>
            <template v-if="highlightMap[data.id]?.highlight">
              <IconifyIconOffline
                v-show="node.label != '全部'"
                v-if="hasAuth('unit:btn:edit')"
                :icon="EditIcon"
                class="ml-2"
                @click.stop="openDialog('编辑', data)"
              />
              <IconifyIconOffline
                v-show="node.label != '全部'"
                v-if="hasAuth('unit:btn:delet')"
                :icon="DelIcon"
                class="text-red-500 ml-2"
                @click.stop="delTree(data)"
              />
            </template>
          </div>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-divider) {
  margin: 0;
}

:deep(.el-tree) {
  --el-tree-node-hover-bg-color: transparent;
}
:deep(.el-tree-node) {
  .el-tree-node__content {
    height: 30px;
  }
}
</style>
